package com.ddzj.scaffold.controller;

import com.ddzj.scaffold.dto.LoginDto;
import com.ddzj.scaffold.entity.User;
import com.ddzj.scaffold.service.UserService;
import com.ddzj.scaffold.utils.JWTUtil;
import com.ddzj.scaffold.vo.AjaxResultVo;
import com.ddzj.scaffold.vo.UserInfoVo;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:yangzibo
 * @CreateTime:2024-04-14 13:57
 * @Description:
 * @Version:1.0
 **/
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public AjaxResultVo login(@Valid @RequestBody LoginDto loginDto){
        User user = userService.findByAccount(loginDto.getAccount());
        if(user == null){
            return AjaxResultVo.errorMsg("用户不存在");
        }
        if(StringUtils.equals(user.getPwd(), loginDto.getPwd())){
            String token = JWTUtil.generateUserToken(user, null);
            String flushToken = JWTUtil.generateUserFlushToken(user, null);
            UserInfoVo userInfoVo = new UserInfoVo();
            userInfoVo.setId(user.getId());
            userInfoVo.setAccount(user.getAccount());
            userInfoVo.setName(user.getName());
            userInfoVo.setToken(token);
            userInfoVo.setFlushToken(flushToken);
            return AjaxResultVo.ok(userInfoVo);
        }
        return AjaxResultVo.errorMsg("密码错误");
    }

    @RequestMapping("/logout")
    public AjaxResultVo logout(){
       boolean isLogin = SecurityContextHolder.getContext().getAuthentication().isAuthenticated();
        SecurityContextHolder.clearContext();
       return AjaxResultVo.ok();
    }

}
